package com.haizhi.workstation.redis;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * redis的连接池
 * @ConditionalOnBean(RedisConfig.class) 当存在RedisConfig的bean实例的时候
 *  才会创建当前类的实例交个spring管理
 */
@Component
@ConditionalOnBean(RedisConfig.class)
public class JedisPoolFactoryBean implements FactoryBean<JedisPool> {
    @Autowired
    private RedisConfig redisConfig;
    @Override
    public JedisPool getObject() throws Exception {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(redisConfig.getPoolMaxTotal());
        config.setMaxIdle(redisConfig.getPoolMaxIdle());
        config.setMaxWaitMillis(redisConfig.getPoolMaxWait()*1000);
        JedisPool pool = new JedisPool(config,redisConfig.getHost(),redisConfig.getPort(),redisConfig.getTimeout(),redisConfig.getPassword());
        return pool;
    }

    @Override
    public Class<?> getObjectType() {
        return JedisPool.class;
    }
}
